using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace GGEditor.Core.Plugins
{
	public class PluginAssemblyManager
	{
		private static PluginAssemblyManager instance = new PluginAssemblyManager();

		private PluginAssemblyManager() { }

		public static PluginAssemblyManager Instance
		{
			get { return instance; }
		}

		private IDictionary<string, Assembly> assemblyCache = new Dictionary<string, Assembly>();

		public Assembly LoadAssembly(string fileName, params string[] dirPaths)
		{
			string filePath = FindAssembly(fileName, dirPaths);
			if (assemblyCache.ContainsKey(filePath))
				return assemblyCache[filePath];
			assemblyCache[filePath] = Assembly.LoadFile(filePath);
			return assemblyCache[filePath];
		}

		private string FindAssembly(string fileName, string[] dirPaths)
		{
			string filePath;

			foreach (string dirPath in dirPaths)
			{
				filePath = Path.Combine(dirPath, fileName);
				if (File.Exists(filePath))
					return filePath;
			}
			
			filePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), fileName);
			if (File.Exists(filePath))
				return filePath;

			throw new FileNotFoundException(fileName);
		}
	}
}